package com.springboot_shopping.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    // 上传文件保存路径
    @Value("${image.upload.path}")
    private String uploadPath;

    // 访问路径前缀
    @Value("${image.access.url}")
    private String accessUrl;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 提取 URL 路径部分,去掉域名
        String urlPath = accessUrl.replaceFirst("http://[^/]+", "");

        // 确保路径以 / 结尾
        if (!urlPath.endsWith("/")) {
            urlPath += "/";
        }

        // 映射规则：/images/** -> file:D:/uploads/
        registry.addResourceHandler(urlPath + "**")
                .addResourceLocations("file:" + uploadPath);
    }
}